<template>
	<view class="main">
		<u-sticky offset-top="0" bgColor="#fff">
			<u-tabs :list="list1" @click="click" :scrollable="isScrollable" lineColor="#1ba784" :activeStyle="{
        color: '#303133',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
    }" :inactiveStyle="{
        color: '#606266',
        transform: 'scale(1)'
    }" :itemStyle="{ height:'42px' }">
			</u-tabs>
		</u-sticky>
		<view class="body">
			<view class="content" v-show="resultList.length">
				<view class="sportContent" v-for="(item,index) in resultList" :key="item.id"
					@click="gotoDetails(item.id)">
					<remindComponents :item="item"></remindComponents>
				</view>
			</view>
			<view v-show="this.resultList.length==0&&this.flag==0" class="drugSuggestion">
				<view class="drugsList">
					<view v-for="(item,index) in drugsList" :key="item.id" class="drugChildren">
						<u-row>
							<u-col span="3" align="center">
								<view class="demo-layout bg-purple-light">
									<u-tag text="药品名:"></u-tag>
								</view>
							</u-col>
							<u-col span="3" align="center">
								<view class="demo-layout bg-purple">{{item.name}}</view>
							</u-col>
							<u-col span="3" align="center">
								<view class="demo-layout bg-purple">
									<u-tag text="提醒时间:"></u-tag>
								</view>
							</u-col>
							<u-col span="2" align="center">
								<view class="demo-layout bg-purple">
									{{item.date}}
								</view>
							</u-col>
							<u-col span="1" align="center">
								<u-icon name="trash" @click="dropDrug(item)"></u-icon>
							</u-col>
						</u-row>
					</view>
				</view>
				<view class="drugAddForm">
					<u--form labelPosition="left" :model="formData" :rules="rules" ref="uForm">
						<u-form-item label="药品名:" prop="name" borderBottom ref="item1" labelWidth="auto">
							<u--input v-model="formData.name" border="none"></u--input>
						</u-form-item>
						<u-form-item label="提醒时间:" prop="date" borderBottom ref="item1" labelWidth="auto">
							<!-- <u--input v-model="formData.date" border="none"></u--input> -->
							<u--text :text="formData.date"></u--text>
							<u-icon name="calendar" size="24px" @click="DateTimePickerClick()"></u-icon>
						</u-form-item>
					</u--form>
					<view class="submitButton">
						<u-button @click="submitDrug()" text="保存" color="#3c9cff" shape="circle"></u-button>
					</view>
				</view>
				<!-- 推荐药品选择列表 -->
				<view class="drugs">
					<u-picker :show="drugsShow" :title="pickerTitle" :columns="pickerColumns" @cancel="pickerCancel"
						@confirm="pickerConfirm" @change="changeHandler">
					</u-picker>
					<view class="pickerButton">
						<u-button @click="pickerClick()" text="选择药品" color="#1ba784" shape="circle"></u-button>
					</view>
				</view>
				<!-- 时间选择控件 -->
				<view class="DateTimePicker">
					<u-datetime-picker :show="DateTimeButton" v-model="DateTimePickerValue" mode="time" title="时分"
						@confirm="DateTimePickerConfirm" @cancel="DateTimePickerCancel"></u-datetime-picker>
					<view class="DateTimePickerButton">
						<u-button @click="DateTimePickerClick()" text="选择时间" color="#1ba784" shape="circle">
						</u-button>
					</view>
				</view>
			</view>
			<view class="empty">
				<u-empty mode="data" v-show="!this.resultList.length&&(this.flag!=0)">
				</u-empty>
			</view>
		</view>
	</view>
</template>

<script>
	// 引入nanoid
	import {
		nanoid
	} from 'nanoid';
	export default {
		data() {
			return {
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '药品名不能为空',
						trigger: ['blur']
					},
					'date': {
						type: 'string',
						required: true,
						message: '提醒时间不能为空',
						trigger: ['blur']
					},
				},
				//发送请求获取html文本内容
				content: `<p>露从今夜白，月是故乡明</p><img src="https://cdn.uviewui.com/uview/swiper/2.jpg" />`,
				//tags是否可滚动
				isScrollable: false,
				list1: [{
					name: '用药提醒',
					id: "1"
				}, {
					name: '运动',
					id: "2"
				}, {
					name: '饮食',
					id: "3"
				}, {
					name: '养生',
					id: "4"
				}, ],
				resultList: [],
				//url映射
				resultMap: ["/yongyao", "/sport", "/dish", "/yangsheng"],
				//保存点击时的索引
				clickIndex: 0,
				// 药物列表集合
				drugsList: [],
				// 控制日期控件的打开
				drugsShow: false,
				// 标志量
				flag: 2,
				pickerTitle: "用药选择",
				pickerColumns: [
					["降压药", "降糖药", "调脂药", "镇痛药", "抗抑郁药", "胃药", "抗过敏药", "维生素和矿物质"],
					['氢氯噻嗪', '美托洛尔', '氨氯地平', '贝那普利', '氯沙坦']
				],
				columnData: [
					['氢氯噻嗪', '美托洛尔', '氨氯地平', '贝那普利', '氯沙坦'],
					['二甲双胍', '胰岛素', '格列本脲', '吡格列酮', '格列齐特'],
					['辛伐他汀', '阿托伐他汀'],
					['扑热息痛', '布洛芬', '可待因', '吗啡'],
					['氟西汀', '帕罗西汀'],
					['奥美拉唑', '兰索拉唑', '雷尼替丁', '法莫替丁'],
					['非索非那定', '西替利嗪'],
					['维生素D', '钙片', '铁剂', '复合维生素B']
				],
				formData: {
					id: "",
					category: null,
					name: null,
					date: "",
				},
				//日期控件的开关
				DateTimeButton: false,
				//日期控件的值
				DateTimePickerValue: "",
				// 药品列表
				drugsList: []
			};
		},

		onReady() {
			//onReady 为uni-app支持的生命周期之一
			// 设置表单校验rule
			this.$refs.uForm.setRules(this.rules)
		},
		onLoad() {
			//如果此时的flag==0,从缓存中加载值
			if (this.flag === 0) {
				this.balanceDrugListStorage()
			}
		},
		onPullDownRefresh() {
			uni.stopPullDownRefresh()
		},
		methods: {
			changeHandler(e) {
				// 测试,后期删除
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index, //第一列的索引下标
					indexs,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// picker为选择器this实例，变化第二列对应的选项
				picker.setColumnValues(1, this.columnData[indexs[0]])
			},
			// 药品控件取消点击事件
			pickerCancel() {
				this.drugsShow = false;
			},
			// 药品控件确认点击事件
			pickerConfirm(data) {
				this.formData.category = data.value[0];
				this.formData.name = data.value[1];
				this.drugsShow = false;
			},
			// 药品控件控制方法
			pickerClick() {
				this.drugsShow = !this.drugsShow;
			},
			//日期控件控制方法
			DateTimePickerClick() {
				this.DateTimeButton = !this.DateTimeButton;
			},
			//日期控件的confirm
			DateTimePickerConfirm(value) {
				console.log(value)
				this.formData.date = value.value
				this.DateTimeButton = false;
			},
			//日期控件的cancel事件
			DateTimePickerCancel() {
				this.DateTimeButton = false;
			},
			// 控制去往详情页的的方法
			gotoDetails(id) {
				uni.navigateTo({
					url: `/pages/details/remindDetails?id=${id}&type=${this.clickIndex}`
				})
			},
			click(item) {
				if (item.index == 0 || item.index == 3) {
					this.resultList = [];
					this.flag = item.index;
					this.balanceDrugListStorage();
					return;
				}
				this.flag = item.index;
				this.clickIndex = item.index;
				//发起网络请求
				this.$request(`${this.resultMap[item.index]}/query`, "GET", {}, {}).then(res => {
					this.resultList = res.data.data.records;
				}).catch(error => {
					console.log(`${error}`);
				})
			},
			//滚动事件
			scrollEvent(scrollTop) {},
			//上拉触底事件
			scrolltolower() {},
			// 表单校验
			submitDrug() {
				this.$refs.uForm.validate().then(res => {
					// 生成长度为10位的nanoid
					this.formData.id = nanoid(10);
					//校验通过,psuh
					this.drugsList.push(this.formData)
					this.formData = {}
					this.setDrugListStorage()
				}).catch(errors => {})
			},
			dropDrug(data) {
				//遍历drugsList
				this.drugsList = this.drugsList.filter(t => t.id != data.id);
				this.setDrugListStorage()
			},
			// 将drugs的数据保存到缓存,
			setDrugListStorage() {
				uni.setStorageSync("drugsList", this.drugsList);
			},
			//同步缓存
			balanceDrugListStorage() {
				this.drugsList = uni.getStorageSync("drugsList");
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		.sportContent {
			padding: 2% 5%;

			border-bottom: 1px dotted #efefef;
		}
	}

	.drugSuggestion {
		margin-top: 3%;

		.drugAddForm {
			margin-top: 5%;
			margin-left: 5%;
			margin-right: 5%;

			.submitButton {
				margin-top: 5%;
				padding: 0% 30%;
			}
		}

		.drugsList {
			margin-left: 2%;
			margin-right: 2%;

			.drugChildren {
				padding: 4rpx 10rpx;
				height: 60rpx;
				background-color: #e2e1e4;
				margin-top: 5rpx;
				text-align: left;
				align-content: center;
				line-height: 60rpx;
				font-size: 14px;
				border-radius: 10rpx;

				.tag {
					width: 20rpx;
					height: 100%;
				}
			}
		}

		.drugs {
			.pickerButton {
				padding: 0 30%;
				margin-top: 10%;
			}
		}

		.DateTimePicker {
			.DateTimePickerButton {
				padding: 0 30%;
				margin-top: 10%;
			}
		}
	}

	.empty {
		margin-top: 45%;
	}

	.demo-layout {
		height: 60rpx;
		border-radius: 4px;
	}

	.bg-purple {}

	.bg-purple-light {}

	.bg-purple-dark {}
</style>